#import "XMLParser.h"
#import "XMLNode.h"
#import "XMLInternalNode.h"
#import "XMLLeafNode.h"

@implementation XMLParser

- (XMLNode *)parse:(NSData *)xml error:(NSError **)err
{
    rootNode = [[XMLNode alloc] init];
    currentNode = rootNode;
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xml];
    parser.delegate = self;
    if ([parser parse] == NO)
    {
        if (err == nil)
        {
            [rootNode release];
            rootNode = nil;
        }
        else
            *err = [[[parser parserError] retain] autorelease];
    }
    else
    {
        if (err != nil)
            *err = nil;
    }
    [parser release];
    return [rootNode autorelease];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qualifiedName
    attributes:(NSDictionary *)attributes
{
    XMLInternalNode *node = [[XMLInternalNode alloc]
                                 initWithParent:currentNode key:elementName
                                 attributes:attributes];
    [currentNode.children addObject:node];
    [node release];
    currentNode = node;
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qualifiedName
{
    currentNode = currentNode.parent;
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    XMLLeafNode *node = [[XMLLeafNode alloc] initWithParent:currentNode
                             value:string];
    [currentNode.children addObject:node];
    [node release];
}

@end
